package com.wfh.picture.api.aliyunai;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.wfh.picture.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.wfh.picture.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.wfh.picture.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.wfh.picture.exception.BusinessException;
import com.wfh.picture.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author FengHuan Wang
 * @Date 2025/5/16 14:57
 * @Version 1.0
 */
@Slf4j
@Component
public class AliYunAiApi {

    @Value("${aliyunai.access-key}")
    private static String accessKey;

    /**
     * 创建任务地址
     */
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";

    /**
     * 查询任务结果地址
     */
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";


    /**
     * 创建任务
     * @param request
     * @return
     */
    public static CreateOutPaintingTaskResponse createTask(CreateOutPaintingTaskRequest request) {
        // 校验请求参数
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "扩图参数不能为空");
        }
        // 使用Hutool工具类发送请求
        HttpRequest httpRequest;
        CreateOutPaintingTaskResponse taskResponse = new CreateOutPaintingTaskResponse();
        try {
            httpRequest = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                    .header("Authorization", "Bearer " + accessKey)
                    .header("Content-Type", "application/json")
                    .header("X-DashScope-Async", "enable")
                    .body(JSONUtil.toJsonStr(request));
            HttpResponse httpResponse = httpRequest.execute();
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建任务失败");
            }
            taskResponse = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskResponse.class);
            if (taskResponse.getCode() != null) {
                log.error("创建任务失败，错误码：{}，错误信息：{}", taskResponse.getCode(), taskResponse.getMessage());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI扩图失败");
            }
        }catch (Exception e){
            log.error("创建任务失败", e);
        }finally {
            log.info("创建任务结束");
        }
        return taskResponse;
    }

    // 查询创建任务的结果

    /**
     * 查询任务结果
     * @param taskId
     * @return
     */
    public GetOutPaintingTaskResponse getTaskResult(String taskId) {
        if (taskId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务ID不能为空");
        }
        HttpResponse httpResponse  = null;
        HttpRequest httpRequest;
        String url = String.format(GET_OUT_PAINTING_TASK_URL, taskId);
        try {
            httpRequest = HttpRequest.get(url)
                    .header("Authorization", "Bearer " + accessKey);
            httpResponse = httpRequest.execute();
            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取任务失败");
            }
        }catch (Exception e){
            log.error("创建任务失败", e);
        }
        return JSONUtil.toBean(httpResponse.body(), GetOutPaintingTaskResponse.class);
    }
}
